package leetcode.code0640;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public String solveEquation(String equation) {
		int index = equation.indexOf('=');
		int[] v1 = val(equation.substring(0, index));
		int[] v2 = val(equation.substring(index + 1, equation.length()));
		int x = v1[0] - v2[0];
		int n = v2[1] - v1[1];
		if (x == 0) {
			if (n == 0) {
				return "Infinite solutions";
			}
			return "No solution";
		}
		return "x=" + n / x;
	}

	private int[] val(String substring) {
		char[] cs = substring.toCharArray();
		int num = 0, x = 0, val = 0, mul = 1, nx = 0;
		for (int i = 0; i < cs.length; i++) {
			char c = cs[i];
			if (c == 'x') {
				x += nx == 0 ? mul : mul * num;
				num = 0;
			} else if (c == '-') {
				val += mul * num;
				mul = -1;
				num = 0;
				nx = 0;
			} else if (c == '+') {
				val += mul * num;
				mul = 1;
				num = 0;
				nx = 0;
			} else {
				num = num * 10 + c - '0';
				nx = 1;
			}
		}
		val += mul * num;
		return new int[] { x, val };
	}

	@Override
	public void debug4() {
		H.compare("Infinite solutions", this.solveEquation("0x=0"));
		H.compare("x=2", this.solveEquation("2x-36+5-3+x+10=6+4x-2-x+5x"));
		H.compare("x=2", this.solveEquation("x+5-3+x=6+x-2"));
		H.compare("Infinite solutions", this.solveEquation("x=x"));
		H.compare("x=0", this.solveEquation("2x=x"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
